package com.chuantou.yuba.ui;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.baidu.location.BDLocation;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.LoginTO;
import com.chuantou.yuba.api.to.StartAdDataTO;
import com.chuantou.yuba.api.to.StartAdTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.dao.CoverDao;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.UiUtil;

public class SplashActivity extends BaseActivity {
	private static final int WHAT_TO_LOGIN = 0x1;
	private static final int WHAT_TO_MAIN = 0x2;
	private static final int WHAT_COUNTER = 0x3;
	private static final int WHAT_TO_UPDATE_PROFILE = 0x4;
	private ImageView mCoverView;
	private int mCount = 4;
	private View mSkipView;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			clearAllMessage();
			switch (msg.what) {
			case WHAT_TO_LOGIN: {
				Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
				startActivity(intent);
				finish();
			}
				break;
			case WHAT_TO_MAIN: {
				Intent intent = new Intent(SplashActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				finish();
			}
				break;
			case WHAT_TO_UPDATE_PROFILE: {
				Intent intent = new Intent(SplashActivity.this, UpdateProfileActivity.class);
				startActivity(intent);
				finish();
			}
				break;
			case WHAT_COUNTER: {
				if (!hasDestroyed()) {
					if (mCount > 0) {
						mHandler.sendEmptyMessageDelayed(WHAT_COUNTER, 1000);
						mCount--;
					} else {
						final AccountManager manager = AccountManager.getInstance(getApplicationContext());
						if (manager.isLogined()) {
							UserTO user = manager.getUserTO();
							// 需要补全用户信息
							if (TextUtils.isEmpty(user.getUsername())) {
								mHandler.sendEmptyMessage(WHAT_TO_UPDATE_PROFILE);
							} else {
								mHandler.sendEmptyMessage(WHAT_TO_MAIN);
							}
						} else {
							mHandler.sendEmptyMessage(WHAT_TO_LOGIN);
						}
					}
				}
			}
				break;
			default:
				break;
			}
		}
	};

	private void clearAllMessage() {
		mHandler.removeMessages(WHAT_COUNTER);
		mHandler.removeMessages(WHAT_TO_MAIN);
		mHandler.removeMessages(WHAT_TO_LOGIN);
		mHandler.removeMessages(WHAT_TO_UPDATE_PROFILE);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		YBApp.get().startLocate(null);
		setContentView(R.layout.splash);
		mCoverView = (ImageView) findViewById(R.id.cover);
		mSkipView = findViewById(R.id.skip);
		mSkipView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				clearAllMessage();
				mCount = 0;
				mHandler.sendEmptyMessage(WHAT_COUNTER);
			}
		});
		final AccountManager manager = AccountManager.getInstance(getApplicationContext());
		loadCover();
		if (manager.isLogined()) {
			// 先定位
			new AsyncTask<Void, Void, BDLocation>() {
				private CountDownLatch mLatch = new CountDownLatch(1);

				@Override
				protected BDLocation doInBackground(Void... params) {
					BDLocation location = YBApp.get().getLocation();
					try {
						int waitCount = 0;
						while (location == null) {
							mLatch.await(1, TimeUnit.SECONDS);
							location = YBApp.get().getLocation();
							// 3秒后无结果直接返回
							if (waitCount >= 3) {
								break;
							}
							waitCount++;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return location;
				}

				protected void onPostExecute(BDLocation location) {
					refreshToken(location);
					mHandler.sendEmptyMessageDelayed(WHAT_TO_MAIN, 3 * 1000);
				};
			}.execute();
		} else {
			// 跳转到登录界面
			mHandler.sendEmptyMessageDelayed(WHAT_TO_LOGIN, 3 * 1000);
		}
	}

	private void loadCover() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				Context context = getApplicationContext();
				List<StartAdTO> covers = CoverDao.getAllCover(getApplicationContext());
				requestCover(covers);
				Bitmap bitmap = null;
				if (covers != null && !covers.isEmpty()) {
					StartAdTO cover = covers.get(0);
					String url = cover.getImage();
					ImageCache cache = BitmapBinder.getImageLoader(context).getImageCache();
					bitmap = cache.getBitmap(url);
					if (bitmap == null) {
						byte[] data = CoverDao.getCoverBitmap(context, cover.getId());
						if (data != null) {
							bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
						}
						// 放入缓存中
						cache.putBitmap(url, bitmap);
					}
				}
				displayCover(bitmap);
			}
		}).start();
	}

	private void displayCover(final Bitmap bitmap) {
		if (hasDestroyed())
			return;
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (bitmap != null) {
					mSkipView.setVisibility(View.VISIBLE);
					mCoverView.setImageBitmap(bitmap);
				} else {
					mSkipView.setVisibility(View.GONE);
					mCoverView.setImageResource(R.drawable.splash);
				}
			}
		});
		mHandler.sendEmptyMessage(WHAT_COUNTER);
	}

	private void requestCover(final List<StartAdTO> covers) {
		final Context context = getApplicationContext();
		String url = UriHelper.getStartAdUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_TYPE, "2");
		GsonRequest<StartAdDataTO> request = new GsonRequest<StartAdDataTO>(Method.POST, url, new Listener<StartAdDataTO>() {

			@Override
			public void onResponse(StartAdDataTO response) {
				final StartAdTO startAd = response.getAd();
				long id = startAd == null ? 0 : startAd.getId();
				if (covers != null) {
					for (StartAdTO cover : covers) {
						if (cover.getId() != id) {
							CoverDao.deleteCover(getApplicationContext(), cover.getId());
						}
					}
				}
				if (startAd != null) {
					CoverDao.insertCover(getApplicationContext(), startAd);
					BitmapBinder.getImageLoader(context).get(startAd.getImage(), new ImageListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							CoverDao.deleteCover(context, startAd.getId());
						}

						@Override
						public void onResponse(ImageContainer response, boolean isImmediate) {
							final Bitmap bitmap = response.getBitmap();
							if (bitmap != null) {
								new Thread(new Runnable() {

									@Override
									public void run() {
										CoverDao.insertCoverBitmapByte(context, bitmap, startAd.getId());
									}
								}).start();
							}
						}
					}, UiUtil.getScreenWidth(context), UiUtil.getScreenHeight(context), null);

				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}, params, StartAdDataTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	private void refreshToken(BDLocation location) {
		String url = UriHelper.getRefreshTokenUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		final Context context = getApplicationContext();
		AccountManager accountManager = AccountManager.getInstance(context);
		UserTO user = accountManager.getUserTO();
		if (user == null)
			return;
		params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		params.put(UriHelper.PARAMS_TOKEN, user.getToken());
		GsonRequest<LoginTO> request = new GsonRequest<LoginTO>(Method.POST, url, new Listener<LoginTO>() {

			@Override
			public void onResponse(LoginTO response) {
				if (response != null && response.isSuccess()) {
					UserTO user = response.getUser();
					if (user != null && user.getUid() > 0) {
						user.setLoginTime(System.currentTimeMillis());
						AccountManager.saveUser(context, user);
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}, params, LoginTO.class);
		RequestManager.startRequest(context, request);
	}

	@Override
	public void onBackPressed() {
	}

}
